package com.cus.tom.transfer.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.cus.tom.transfer.ac.ChooseAct;
import com.cus.tom.transfer.ac.ListAct;
import com.cus.tom.transfer.databinding.ChooseItemBinding;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.ArrayList;
import java.util.List;

public class ChooseAdapter {

    String[] ss = new String[]{"图片", "视频", "音乐", "软件"};
    LinearLayout linearLayout;
    List<ChooseItemBinding> list = new ArrayList<>();
    ChooseAct act;

    public ChooseAdapter(LinearLayout linearLayout, ChooseAct act) {
        this.linearLayout = linearLayout;
        this.act = act;
        linearLayout.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(linearLayout.getContext());
        for (int i = 0; i < ss.length; i++) {
            ChooseItemBinding binding = ChooseItemBinding.inflate(inflater, linearLayout, true);
            list.add(binding);
            binding.title.setText(ss[i]);
            updateItem(i);
        }
    }

    public void notifyItemChanged(int index, long... param) {
        list.get(index).size.setText(Utils.formatSize(param[1]));
        if (param.length > 2) {
            list.get(index).num.setText("(" + param[2] + "/" + param[0] + ")");
        } else {
            list.get(index).num.setText("(0/" + param[0] + ")");
        }
        list.get(index).getRoot().setOnClickListener(v -> {
            Intent i = new Intent(act, ListAct.class);
            i.putExtra("index", index);
            act.startActivityForResult(i, index);
        });
        list.get(index).check.setOnClickListener(v -> {
            boolean bo = !v.isSelected();
            v.setSelected(bo);
            act.updateSelect(index, bo);
        });
    }

    public void checkTypeFile(int i) {
        boolean bo = list.get(i).check.isSelected();
        if (bo) {
            return;
        }
        list.get(i).check.setSelected(true);
        act.updateSelect(i, true);
    }

    private void updateItem(int i) {
        checkPermission(list.get(i), Permission.MANAGE_EXTERNAL_STORAGE);
        list.get(i).btn.setOnClickListener(v -> {
            act.askPermission(i);
        });
    }

    private void checkPermission(ChooseItemBinding binding, String permission) {
        if (XXPermissions.isGranted(linearLayout.getContext(), permission)) {
            binding.btn.setVisibility(View.INVISIBLE);
        } else {
            binding.btn.setVisibility(View.VISIBLE);
        }
    }
}
